// 个人中心
const path = require('path');
const db = require(path.join(__dirname, '../common/db.js'));
const utility = require('utility');
const express = require('express');
const router = express.Router();

// 获取用户基本信息
router.get('/userinfo', async (res, req) => {
    let sql = 'select id, username, nickname, email, user_pic from user where id = ?';
    let ret = await db.db(sql, res.user.id);
    if (ret.length > 0) {
        req.json({
            status: 0,
            message: '获取用户信息成功',
            data: ret[0]
        })
    } else {
        req.json({
            status: 1,
            message: '获取用户信息失败'
        })
    }
})

// 更新用户基本信息
router.post('/userinfo', async (res, req) => {
    let params = res.body;
    let sql = 'update user set ? where id = ?';
    let ret = await db.db(sql, [
        {
            nickname: params.nickname,
            email: params.email,
            user_pic: params.user_pic
        },
        params.id
    ]);
    if (ret.affectedRows > 0) { // 更新成功
        req.json({
            status: 0,
            message: '更新用户信息成功'
        })
    } else {
        req.json({
            status: 1,
            message: '更新用户信息失败'
        })
    }
})

// 重置密码
router.post('/updatepwd', async (res, req) => {
    let params = res.body;
    params.oldPwd = utility.md5(params.oldPwd);
    params.newPwd = utility.md5(params.newPwd);
    let sql = 'update user set password = ? where id = ? and password = ?';
    let ret = await db.db(sql, [
        params.newPwd,
        res.user.id,
        params.oldPwd
    ]);
    if (ret.affectedRows > 0) { // 更新成功
        req.json({
            status: 0,
            message: '重置密码成功'
        })
    } else {
        req.json({
            status: 1,
            message: '重置密码失败'
        })
    }
})

// 更换头像
router.post('/update/avatar', async (res, req) => {
    let sql = 'update user set user_pic = ? where id = ?';
    let ret = await db.db(sql, [
        res.body.avatar,
        res.user.id
    ]);
    if (ret.affectedRows > 0) { // 更新成功
        req.json({
            status: 0,
            message: '更换头像成功'
        })
    } else {
        req.json({
            status: 1,
            message: '更换头像失败'
        })
    }
})

module.exports = router;